package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
	"vehicle-data-mgr/cache"
	"vehicle-data-mgr/models"
	"vehicle-data-mgr/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "参数不能为空",
		})
		return
	}
	var user models.User
	redis_key := "user_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount == 3 {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "密码错误3次，账号已封禁",
		})
		return
	}
	err := models.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "查询失败，账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(http.StatusInternalServerError, gin.H{
				"code": 500,
				"msg":  "密码错误3次,账号封禁2小时",
			})
			return
		}

		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var role []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid=roles.id").
		Where("user_roles.uid", uid).Debug().
		Find(&role)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
	return
}

func RoleNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var node []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid=nodes.id").
		Where("role_nodes.rid", rid).Debug().
		Find(&node)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
	return
}
